package com.yuhong.springbootinit.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.yuhong.springbootinit.annotation.AuthCheck;
import com.yuhong.springbootinit.common.BaseResponse;
import com.yuhong.springbootinit.common.DeleteRequest;
import com.yuhong.springbootinit.common.ErrorCode;
import com.yuhong.springbootinit.common.ResultUtils;
import com.yuhong.springbootinit.constant.UserConstant;
import com.yuhong.springbootinit.exception.BusinessException;
import com.yuhong.springbootinit.exception.ThrowUtils;
import com.yuhong.springbootinit.model.dto.position.*;
import com.yuhong.springbootinit.model.entity.CompanyPosition;
import com.yuhong.springbootinit.model.entity.CompanyUser;
import com.yuhong.springbootinit.model.entity.Position;
import com.yuhong.springbootinit.model.enums.PositionStatusEnum;
import com.yuhong.springbootinit.model.vo.PositionVO;
import com.yuhong.springbootinit.service.CompanyPositionService;
import com.yuhong.springbootinit.service.CompanyUserService;
import com.yuhong.springbootinit.service.PositionService;
import com.yuhong.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/position")
@Slf4j
@CrossOrigin
public class PositionController {

    @Resource
    private PositionService positionService;

    @Resource
    private UserService userService;

    @Resource
    private CompanyUserService companyUserService;

    @Resource
    private CompanyPositionService companyPositionService;


    /**
     * 创建
     *
     * @param positionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addPosition(@RequestBody PositionAddRequest positionAddRequest, HttpServletRequest request) {
        if (positionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Position position = new Position();
        BeanUtils.copyProperties(positionAddRequest, position);
        List<String> tags = positionAddRequest.getTags();
        if (tags != null) {
            position.setTags(JSONUtil.toJsonStr(tags));
        }
        List<String> requirement = positionAddRequest.getRequirement();
        if (requirement != null) {
            position.setRequirement(JSONUtil.toJsonStr(requirement));
        }

        positionService.validPosition(position, true);
//        User loginUser = userService.getLoginUser(request);

        position.setPositionId(UUID.randomUUID().toString());
        position.setStatus(PositionStatusEnum.CREATED.getCode());
        position.setUserId(positionAddRequest.getUserId());
        boolean result = positionService.save(position);

        // TODO: 2025/3/13 创建职位的时候同步公司职位关系表
        CompanyUser companyUserInfo = companyUserService.getCompanyInfoByUserId(positionAddRequest.getUserId());

        CompanyPosition companyPosition = new CompanyPosition();
        companyPosition.setCompanyId(companyUserInfo.getCompanyId());
        companyPosition.setPositionId(position.getPositionId());
        boolean saved = companyPositionService.save(companyPosition);

        ThrowUtils.throwIf(!result&&!saved, ErrorCode.OPERATION_ERROR);
        long newPositionId = position.getId();
        return ResultUtils.success(newPositionId);
    }

    @PostMapping("/release")
    public BaseResponse<Long> releasePosition(@RequestBody PositionReleaseRequest positionReleaseRequest){
        Long id = positionReleaseRequest.getId();

        Position position = positionService.updatePositionStatus(id);

        return ResultUtils.success(position.getId());

    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePosition(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
//        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Position oldPosition = positionService.getById(id);
        ThrowUtils.throwIf(oldPosition == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldPosition.getUserId().equals(deleteRequest.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = positionService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param postUpdateRequest
     * @return
     */
    @PostMapping("/update")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePosition(@RequestBody PositionUpdateRequest postUpdateRequest) {
        if (postUpdateRequest == null || postUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Position position = new Position();
        List<String> tags = postUpdateRequest.getTags();
        if (tags != null) {
            position.setTags(JSONUtil.toJsonStr(tags));
        }
        List<String> requirement = postUpdateRequest.getRequirement();
        if (requirement != null) {
            position.setRequirement(JSONUtil.toJsonStr(requirement));
        }
        BeanUtils.copyProperties(postUpdateRequest, position);

        // 参数校验
        positionService.validPosition(position, false);
        long id = postUpdateRequest.getId();
        // 判断是否存在
        Position oldPosition = positionService.getById(id);
        ThrowUtils.throwIf(oldPosition == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = positionService.updateById(oldPosition);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<PositionVO> getPositionVOById(long id, HttpServletRequest request) throws JsonProcessingException {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Position position = positionService.getById(id);
        if (position == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(positionService.getPositionVO(position, request));
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param postQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Position>> listPositionByPage(@RequestBody PositionQueryRequest postQueryRequest) {
        long current = postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize();
        Page<Position> postPage = positionService.page(new Page<>(current, size),
                positionService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success(postPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PositionVO>> listPositionVOByPage(@RequestBody PositionQueryRequest postQueryRequest,
                                                           HttpServletRequest request) {
        long current = postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Position> postPage = positionService.page(new Page<>(current, size),
                positionService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success(positionService.getPositionVOPage(postPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<PositionVO>> listMyPostVOByPage(@RequestBody PositionQueryRequest postQueryRequest,
                                                             HttpServletRequest request) {
        if (postQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
//        User loginUser = userService.getLoginUser(request);
//        postQueryRequest.setUserId(loginUser.getUserAccount());
        long current = postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Position> postPage = positionService.page(new Page<>(current, size),
                positionService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success(positionService.getPositionVOPage(postPage, request));
    }

    // endregion


    /**
     * 编辑（用户）
     *
     * @param postEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editPost(@RequestBody PositionEditRequest postEditRequest, HttpServletRequest request) {
        if (postEditRequest == null || postEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Position position = new Position();
        BeanUtils.copyProperties(postEditRequest, position);
        List<String> tags = postEditRequest.getTags();
        if (tags != null) {
            position.setTags(JSONUtil.toJsonStr(tags));
        }
        List<String> requirement = postEditRequest.getRequirement();
        if (requirement != null) {
            position.setRequirement(JSONUtil.toJsonStr(requirement));
        }
        // 参数校验
        positionService.validPosition(position, false);
//        User loginUser = userService.getLoginUser(request);
        long id = postEditRequest.getId();
        // 判断是否存在
        Position oldPosition = positionService.getById(id);
        ThrowUtils.throwIf(oldPosition == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldPosition.getUserId().equals(postEditRequest.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = positionService.updateById(position);
        return ResultUtils.success(result);
    }

    @GetMapping("/getStatusEnums")
    public BaseResponse<Map<Integer, String>> getPositionStatusEnums(){

        Map<Integer, String> map = new HashMap<>();

        for (PositionStatusEnum statusEnum: PositionStatusEnum.values()) {
            map.put(statusEnum.getCode(), statusEnum.getName());
        }

        return ResultUtils.success(map);
    }

    @GetMapping("/get/my/distinct/vo")
    public BaseResponse<List<PositionVO>> getMyDistinctPost(@RequestParam String userId){

        QueryWrapper<Position> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Position::getUserId, userId);
        queryWrapper.select("DISTINCT title, position_id");
        List<Position> positionList = positionService.list(queryWrapper);
        List<PositionVO> positionVOList = BeanUtil.copyToList(positionList, PositionVO.class);

        return ResultUtils.success(positionVOList);
    }

    @GetMapping("/get/my/company/position")
    public BaseResponse<List<Position>> getMyCompanyPosition(@RequestParam String userId){
        return ResultUtils.success(positionService.getPositionsByUserId(userId)) ;
    }


    @GetMapping("/get/my/position/application")
    public BaseResponse<List<PositionApplicationSimpleDTO>> getSimpleApplicationCountByPosition(@RequestParam String userId){
        return ResultUtils.success(positionService.getSimpleApplicationCountByPosition(userId)) ;
    }

}
